package org.lan.tree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author <p><a href="mailto:1728209643@qq.com">XiaoSan</a>
 * @date 2019/11/26 10:39 AM
 */
public class LC_623 {

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.left.left = new TreeNode(4);
        root.right = new TreeNode(3);
        root.print();
        System.out.println();
        new LC_623().addOneRow(root, 5, 4).print();
    }

    public TreeNode addOneRow(TreeNode t, int v, int d) {
        if (d == 1) {
            TreeNode n = new TreeNode(v);
            n.left = t;
            return n;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(t);
        int depth = 1;
        while (depth < d - 1) {
            Queue<TreeNode> temp = new LinkedList<>();
            while (!queue.isEmpty()) {
                TreeNode node = queue.remove();
                if (node.left != null) temp.add(node.left);
                if (node.right != null) temp.add(node.right);
            }
            queue = temp;
            depth++;
        }
        while (!queue.isEmpty()) {
            TreeNode node = queue.remove();
            TreeNode temp = node.left;
            node.left = new TreeNode(v);
            node.left.left = temp;
            temp = node.right;
            node.right = new TreeNode(v);
            node.right.right = temp;
        }
        return t;
    }

    public TreeNode addOneRow2(TreeNode t, int v, int d) {
        addRow(t, d, 1, v);
        return t;
    }

    private void addRow(TreeNode node, int d, int deep, int v) {
        if (node == null) {
            return;
        }
        if (deep == d - 1) {
            TreeNode temp = node.left;
            node.left = new TreeNode(v);
            node.left.left = temp;
            temp = node.right;
            node.right = new TreeNode(v);
            node.right.right = temp;
        } else {
            addRow(node.left, d, deep + 1, v);
            addRow(node.right, d, deep + 1, v);
        }
    }

}
